package com.rural.bus.driver;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.rural.bus.driver.fragment.BaseFragment;
import com.rural.bus.driver.fragment.MyOrderFragment;
import com.rural.bus.driver.fragment.NewOrderFragment;
import com.rural.bus.driver.model.Order;
import com.rural.bus.driver.net.MyHttpUtil;
import com.rural.bus.driver.net.OnNetCallback;
import com.rural.bus.driver.net.Url;
import com.rural.bus.driver.utils.CommonTools;
import com.rural.bus.driver.utils.MyLocationClient;
import com.rural.bus.driver.utils.ProgressUtil;
import com.rural.bus.driver.view.CommonAlertDialog;
import com.rural.bus.driver.view.CommonAlertDialog.OnDialogDismissListener;

public class MainActivity extends BaseActivity implements OnClickListener {

	private RelativeLayout rl_fragment_content;
	private TextView tv_new_order, tv_my_order;

	private MyOrderFragment myOrderFragment;
	private NewOrderFragment newOrderFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

	}

	@Override
	protected void initView() {
		mBtMiddle.setText("新订单");
		mBtMiddle.setVisibility(View.VISIBLE);
		mBtMiddle.setTextColor(getResources().getColor(R.color.white));

		mBtRight.setText("刷新位置");
		mBtRight.setVisibility(View.VISIBLE);

		mImgLeft.setVisibility(View.VISIBLE);
		mImgLeft.setBackgroundResource(R.drawable.ic_top_bar_bt);

		tv_my_order = (TextView) findViewById(R.id.tv_my_order);
		tv_new_order = (TextView) findViewById(R.id.tv_new_order);

	}

	@Override
	protected void initData() {
		myOrderFragment = new MyOrderFragment();
		newOrderFragment = new NewOrderFragment();
		setFragment(1);

	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if ("new_order".equals(intent.getStringExtra("tag"))) {
			setFragment(1);
			Order order = (Order) intent.getSerializableExtra("order");
			newOrderFragment.addOrderItem(order);
		} else if ("cancel_order".equals(intent.getStringExtra("tag"))) {
			setFragment(2);
			Order order = (Order) intent.getSerializableExtra("order");
			myOrderFragment.showCancelOrderDialog(order);
		} else if ("accept_order".equals(intent.getStringExtra("tag"))) {
			int order_id = intent.getIntExtra("order_id", 0);
			if (order_id != 0) {
				newOrderFragment.removeOrderItemById(order_id);
			}
			setFragment(2);
		} else if("receive_fail".equals(intent.getStringExtra("tag"))){
			int orderid = intent.getIntExtra("order_id", 0);
			if (orderid != 0) {
				newOrderFragment.removeOrderItemById(orderid);
			}
			setFragment(1);
		} else if("balance_charge".equals(intent.getStringExtra("tag"))){
			setFragment(2);
			Order order = (Order) intent.getSerializableExtra("order");
			myOrderFragment.showCompleteCharge(order);
		}else if("cash_charge".equals(intent.getStringExtra("tag"))){
			setFragment(2);
			Order order = (Order) intent.getSerializableExtra("order");
			myOrderFragment.showCompleteCharge(order);
		}else if("new_half_hour_order".equals(intent.getStringExtra("tag"))){
			//对话框提示有半个小时内订单
			String message = intent.getStringExtra("msg");
			CommonAlertDialog dialog = new CommonAlertDialog(this, "我知道了", null, message, new OnDialogDismissListener(){

				@Override
				public void onConfirmClicked() {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onCancelClicked() {
					// TODO Auto-generated method stub
					
				}
				
			});
			dialog.show();
		}
			
	}

	@Override
	protected void setListeners() {

		mImgLeft.setOnClickListener(this);
		mBtRight.setOnClickListener(this);
		tv_my_order.setOnClickListener(this);
		tv_new_order.setOnClickListener(this);

	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.image_left:
			startActivity(MineActivity.class);
			overridePendingTransition(R.anim.slide_right_in, R.anim.slide_right_out);
			break;
		case R.id.button_right:
			final LocationClient locationClient = new LocationClient(getApplicationContext());
			locationClient.setLocOption(MyLocationClient.getInstance(this).getLocationOption());

			locationClient.registerLocationListener(new BDLocationListener() {

				@Override
				public void onReceiveLocation(BDLocation location) {
					double latitude = location.getLatitude();
					double longitude = location.getLongitude();
					MyApplication.instance().curLatitude = latitude;
					MyApplication.instance().curLongtitude = longitude;
					onFreshLocation(latitude, longitude);
					locationClient.stop();
				}
			});
			locationClient.start();
			break;
		case R.id.tv_new_order:

			setFragment(1);
			break;
		case R.id.tv_my_order:

			setFragment(2);
			break;
		default:
			break;
		}

	}

	private void setFragment(int index) {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		if (index == 2) {
//			transaction.replace(R.id.rl_fragment_content, myOrderFragment);
			replaceFrag(myOrderFragment);
		} else {
//			transaction.replace(R.id.rl_fragment_content, newOrderFragment);
			replaceFrag(newOrderFragment);

		}
		transaction.commit();
		clearTabStatus();
		if (index == 2) {
			tv_my_order.setBackgroundResource(R.color.color_green);
			mBtMiddle.setText("待处理订单");
		} else {
			tv_new_order.setBackgroundResource(R.color.color_green);
			mBtMiddle.setText("新订单");
		}
	}
	
	private BaseFragment lastFragment;
	
	private void replaceFrag(BaseFragment fragment){
		FragmentManager fm=getSupportFragmentManager();
		FragmentTransaction ft=fm.beginTransaction();
		if(!fragment.isAdded()){
			ft.add(R.id.rl_fragment_content, fragment);
		}
		if(lastFragment!=null){
			ft.hide(lastFragment);
		}
		ft.show(fragment);
		ft.commit();
		lastFragment=fragment;
	}


	private void clearTabStatus() {
		tv_my_order.setBackgroundResource(R.color.color_title_bar);
		tv_new_order.setBackgroundResource(R.color.color_title_bar);
	}

	private void onFreshLocation(double latitude, double longitude) {
		String regionId = JPushInterface.getRegistrationID(this);

		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("driverId", "" + MyApplication.driverInfo.drivId);
		http.addBodyParm("currentLongtitude", "" + longitude);
		http.addBodyParm("currentLatitude", "" + latitude);
//		http.addBodyParm("status", "0");          // type0("接单状态", 0), type1("运营状态", 1),type2("休息状态", 2);
		if (!CommonTools.isEmpty(regionId)) {
			http.addBodyParm("regionId", regionId);
		}
		ProgressUtil.showProgress(this, "");
		http.send(Url.update_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				ProgressUtil.closeProgress();
				try {
					if (object.get("status").equals("0")) {
						object = object.getJSONObject("result");
						toast("位置已刷新");
					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void fail(String error) {
				ProgressUtil.closeProgress();
			}
		});
	}
	
	private long lastTime;
	
	@Override
	public void onBackPressed() {
		if(System.currentTimeMillis() - lastTime > 2000){
			toast("再按一次退出应用");
			lastTime = System.currentTimeMillis();
			return;
		}
		super.onBackPressed();
	}
}
